package com.nulldev.util.web.YouTubeExtractor.comments;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;

public class CommentMeta {
	public static final Pattern COMMENTS_PATTERN = Pattern.compile("(?<=\\'COMMENTS_TOKEN\\'\\: \\\")(.*)(?=\\\"\\,      \\'GET)");
	public static final Pattern XSRF_ID_PATTERN = Pattern.compile("(?<=XSRF_TOKEN\\'\\: \\\")(.*)(?=\\\"\\,      \\'XSRF_FIELD)");

	private final String pageData;
	private final UniJsonValue pageJson;

	public CommentMeta(final String pageData) {
		this.pageData = pageData;
		final String raw_json0 = "{\""
				+ StringsUtil.substringBetween(pageData, "var ytplayer = ytplayer || {};ytplayer.config = ", ";ytplayer.load = function() {");
		final String raw_json = raw_json0.substring(2, raw_json0.length());
		this.pageJson = (raw_json.startsWith("<!DOCTYPE html>") ? UniJsonValue.object() : UniJsonValue.parse(raw_json, true));
	}

	public String getToken() {
		final Matcher m = COMMENTS_PATTERN.matcher(pageData);
		m.find();
		return m.group();
	}

	public String getXSRF() {
		final Matcher m = XSRF_ID_PATTERN.matcher(pageData);
		m.find();
		return m.group();
	}

	@Override
	public String toString() {
		return "Comments.Metadata[token=" + this.getToken() + ",xsrf=" + this.getXSRF() + ",itct=" + (this.getITCT() == null ? "null" : this.getITCT()) + "]";
	}

	public String getITCT() {
		try {
			return this.pageJson.get("args").getString("itct");
		} catch (Exception e) {
			JVM.errorln(e);
			return null;
		}
	}
}
